package com.example.remotebomb23;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.telephony.ServiceState;


public class StateReceiver extends BroadcastReceiver  {
	
	public static final String LOG_TAG = "StateReceiver";
	public static final String SIM_STATE_ACTION = "android.intent.action.SIM_STATE_CHANGED";
	public static final String SERVICE_STATE_ACTION = "android.intent.action.SERVICE_STATE";
	public static final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
	private Context mContext = null;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		mContext = context;
		TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
		Log.d(LOG_TAG, "[onReceive][The recive intent is :"+action+"]");
		if (SIM_STATE_ACTION.equals(action)) {
			Log.d(LOG_TAG, "[onReceive][receive SIM_STATE_CHANGED intent]");
			// when sim ready get sim imsi number in delay 10s
			if (tm == null) {
				Log.d(LOG_TAG, "[onReceive][get tm is null]");
				return ;
			}
			String iccimsi = tm.getSubscriberId();
			if (iccimsi != null && iccimsi.trim().length() > 10) {
				// compare the imsi with the old imsi which was saved in SharedPreferences
				SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(mContext);
				if (spf != null) {
					String saved = spf.getString("owner_imsi", "");
					if (saved != null && saved.trim().length() > 0) {
						if (!saved.equals(iccimsi)) {
							// send sms to the bakcup phone number if this number was set
							Intent startservice = new Intent(BombService.ACTION_SEND_MSG_TO_BACKUP_PHONE);
							startservice.setClass(mContext, BombService.class);
							mContext.startService(startservice);
						}
					}
				}
			}
		} else if (SERVICE_STATE_ACTION.equals(action)) {
			Log.d(LOG_TAG, "[onReceive][receive SERVICE_STATE intent]");
			// when in service , start to set sms observer to monitor sms db
			if (tm == null) {
				Log.d(LOG_TAG, "[onReceive][get tm is null]");
				return ;
			}
			Intent startservice = new Intent(BombService.ACTION_START_REGISTER);
			startservice.setClass(mContext, BombService.class);
			mContext.startService(startservice);
		} else if (BOOT_COMPLETED_ACTION.equals(action)) {
			Log.d(LOG_TAG, "[onReceive][receive BOOT_COMPLETED intent]");
			// record boot complete status,
			// when device support quick boot, we couldn't receive boot-completed intent in some devices
			
		} else {
			Log.d(LOG_TAG, "[onReceive][Receive wrong intent]");
		}	
	}
	
	
}
